<template>
  <div class="app-container">
    <div>
      <el-button type="primary" icon="el-icon-plus" @click="handleAddNewProcessDefinitionButton()">新增</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="handleMultipartDelete()">删除</el-button>
    </div>

    <el-table
      ref="multipleTable"
      :data="bpmnList"
      border
      tooltip-effect="dark"
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        align="center"
        width="55">
      </el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="55"
        align="center"
        sortable>
      </el-table-column>
      <el-table-column
        prop="name"
        align="center"
        label="模板名称">
      </el-table-column>
      <el-table-column
        prop="bpmnId"
        align="center"
        label="模板标识">
      </el-table-column>
      <el-table-column
        prop="sort"
        align="center"
        label="排序"
        width="100">
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        align="center"
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleMakeProcess(scope.row.bpmnId)">流程设计</el-button>
          <el-button type="text" size="small" @click="handleAddAuth(scope.row.key)">启动权限</el-button>
          <el-dropdown>
            <el-button type="text" size="small">更多<i class="el-icon-caret-bottom"></i></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleUpdateProcessStatus(scope.row.status, scope.row.key)">{{ scope.row.status ? '停用' : '启用' }}</el-dropdown-item>
              <el-dropdown-item @click.native="handleUpdateProcess(scope.row.id)">修改</el-dropdown-item>
              <el-dropdown-item @click.native="handleDeleteProcess(scope.row.id)">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.page + 1"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="query.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total" style="float: right; margin-top: 20px;">
    </el-pagination>

    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body
               :show-close="false"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入流程名称" maxlength="30" />
        </el-form-item>
        <el-form-item label="流程标识" prop="bpmnId" v-if="title === '新增'">
          <el-input v-model="form.bpmnId" placeholder="请输入流程标识" maxlength="30" />
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAddNewProcessDefinition()">确 定</el-button>
        <el-button @click="handleCancelAdd()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {
  checkBpmnIdUnique,
  deleteProcessBpmn,
  insertProcessBpmn,
  selectProcessBpmn,
  selectProcessBpmnInfo, updateProcessBpmn
} from "@/api/camunda/bpmn";

export default {
  name: "index",
  data() {
    return {
      bpmnList: [],
      query: {
        page: 0,
        size: 10
      },
      total: 0,

      open: false,
      title: '',
      form: {
        id: undefined,
        name: '',
        bpmnId: '',
        sort: 0
      },
      rules: {
        name: [
          {required: true, message: "字段描述不能为空", trigger: "blur"},
          {min: 5, max: 20, message: '字段描述长度必须介于 5 和 20 之间', trigger: 'blur'}
        ],
        bpmnId: [
          {required: true, trigger: "blur", validator: this.bpmnIdRules}
        ]
      },
    }
  },
  created() {
    this.init()
  },
  methods: {
    init(){
      // 初始化流程定义列表
      selectProcessBpmn(this.query)
        .then(({data}) => {
          this.total = data.total
          this.bpmnList = data.rows
        }).catch()
    },
    handleCurrentChange(val) {
      this.query.page = val - 1
      this.init()
    },
    handleSizeChange(val) {
      this.query.size = val
      this.init()
    },
    handleSelectionChange(val) {
      this.selectUserList = val;
    },
    handleMakeProcess(bpmnId) {
      
    },
    handleUpdateProcessStatus(status, key){
      // const txt = status ? '停用' : '启用'
      // updateProcessStatus(key)
      //   .then(() => {
      //     this.$message({
      //       type: 'success',
      //       message: txt + '成功!'
      //     })
      //     this.init()
      //   }).catch(() => {
      //   this.$message({
      //     type: 'error',
      //     message: txt + '失败!'
      //   })
      // })
    },
    handleAddNewProcessDefinitionButton(){
      this.resetProcessForm()
      this.title = '新增'
      this.open = true
    },
    handleAddNewProcessDefinition(){
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id === undefined) {
            insertProcessBpmn(this.form)
              .then(() => {
                this.$message({type: 'success', message: '添加成功!'})
                this.open = false
                this.init();
              }).catch()
          } else {
            updateProcessBpmn(this.form)
              .then(() => {
              this.$message({type: 'success', message: '修改成功!'})
              this.open = false
              this.init();
            }).catch()
          }
        }
      });

    },
    handleCancelAdd(){
      this.open = false
      this.$refs.form.resetFields();
    },
    resetProcessForm(){
      this.form = {
        id: undefined,
        name: '',
        bpmnId: '',
        sort: 0,
      }
    },
    handleMultipartDelete(){
      const ids = []
      this.selectUserList.forEach((item) => {
        ids.push(item.id)
      })
      if(!ids.length > 0){
        this.$message({type: 'warning', message: '请选择要删除的选项'})
        return;
      }

      this.$confirm('共选中'+ ids.length +'项，此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProcessBpmn(ids)
          .then(() => {
            this.$message({type: 'success', message: '删除成功!'})
            this.init();
          }).catch()
      }).catch()
    },
    handleUpdateProcess(id) {
      this.resetProcessForm()
      this.title = '修改'
      this.open = true
      selectProcessBpmnInfo(id)
        .then(({data}) => {
          this.form = data
        })
    },
    handleDeleteProcess(id){
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProcessBpmn(id)
          .then(() => {
            this.$message({type: 'success', message: '删除成功!'})
            this.init();
          }).catch()
      }).catch(() => {})
    },
    bpmnIdRules(rule, value, callback) {
      if (value.length < 5 || value.length > 20) {
        callback(new Error('表单标识长度必须介于 5 和 20 之间'))
      } else {
        let promiseList = []
        const promise = checkBpmnIdUnique(value)
          .then(({data}) => {
            if(data === '0'){
              callback()
            } else {
              callback(new Error('流程定义标识已存在'))
            }
          }).catch()
        promiseList.push(promise)

        Promise.all(promiseList).then(() => {
          callback()
        }).catch()
      }
    },
  },
}
</script>

<style scoped>
.module {
  position: absolute;
  top: 70px;
  left: 0;
  width: 100%;
  padding: 0;
}
.download{
  display: inline-block;
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  width: 89px;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin: 10px;
  text-align: center;
}
.download:hover{
  color: #409eff;
  border: 1px solid #409eff;
  cursor: pointer;
}
</style>
